import { Response } from 'express';
import { AuthenticatedRequest } from '@/middleware/auth';
import { LocationService } from '@/services/locationService';
import { OilPriceService } from '@/services/oilPriceService';
import { LocationQuery, OilPriceByLocationRequest } from '@/types/location';

/**
 * @swagger
 * /api/location/provinces:
 *   get:
 *     summary: 获取所有省份列表
 *     tags: [地理位置]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 获取成功
 *       500:
 *         description: 服务器内部错误
 */
export const getAllProvinces = async (
  _req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const locationService = LocationService.getInstance();
    const provinces = locationService.getAllProvinces();

    res.status(200).json({
      success: true,
      message: '获取省份列表成功',
      data: provinces,
      totalCount: provinces.length,
    });
  } catch (error) {
    console.error('获取省份列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取省份列表失败',
      error: error instanceof Error ? error.message : '未知错误',
    });
  }
};

/**
 * @swagger
 * /api/location/cities/{provinceCode}:
 *   get:
 *     summary: 根据省份代码获取城市列表
 *     tags: [地理位置]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: provinceCode
 *         required: true
 *         schema:
 *           type: string
 *         description: 省份代码
 *     responses:
 *       200:
 *         description: 获取成功
 *       500:
 *         description: 服务器内部错误
 */
export const getCitiesByProvince = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { provinceCode } = req.params;

    if (!provinceCode) {
      res.status(400).json({
        success: false,
        message: '省份代码不能为空',
      });
      return;
    }

    const locationService = LocationService.getInstance();
    const cities = locationService.getCitiesByProvince(provinceCode);

    res.status(200).json({
      success: true,
      message: '获取城市列表成功',
      data: cities,
      totalCount: cities.length,
    });
  } catch (error) {
    console.error('获取城市列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取城市列表失败',
      error: error instanceof Error ? error.message : '未知错误',
    });
  }
};

/**
 * @swagger
 * /api/location/districts/{cityCode}:
 *   get:
 *     summary: 根据城市代码获取区县列表
 *     tags: [地理位置]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: cityCode
 *         required: true
 *         schema:
 *           type: string
 *         description: 城市代码
 *     responses:
 *       200:
 *         description: 获取成功
 *       500:
 *         description: 服务器内部错误
 */
export const getDistrictsByCity = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { cityCode } = req.params;

    if (!cityCode) {
      res.status(400).json({
        success: false,
        message: '城市代码不能为空',
      });
      return;
    }

    const locationService = LocationService.getInstance();
    const districts = locationService.getDistrictsByCity(cityCode);

    res.status(200).json({
      success: true,
      message: '获取区县列表成功',
      data: districts,
      totalCount: districts.length,
    });
  } catch (error) {
    console.error('获取区县列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取区县列表失败',
      error: error instanceof Error ? error.message : '未知错误',
    });
  }
};

/**
 * @swagger
 * /api/location/search:
 *   get:
 *     summary: 搜索地理位置
 *     tags: [地理位置]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: province
 *         schema:
 *           type: string
 *         description: 省份名称或代码
 *       - in: query
 *         name: city
 *         schema:
 *           type: string
 *         description: 城市名称或代码
 *       - in: query
 *         name: district
 *         schema:
 *           type: string
 *         description: 区县名称或代码
 *       - in: query
 *         name: keyword
 *         schema:
 *           type: string
 *         description: 搜索关键词
 *       - in: query
 *         name: fuzzy
 *         schema:
 *           type: boolean
 *           default: true
 *         description: 是否模糊搜索
 *     responses:
 *       200:
 *         description: 搜索成功
 *       500:
 *         description: 服务器内部错误
 */
export const searchLocations = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const {
      province,
      city,
      district,
      keyword,
      fuzzy = 'true',
    } = req.query as LocationQuery;
    const isFuzzy = fuzzy === 'true';

    const locationService = LocationService.getInstance();
    const results = locationService.searchLocations({
      province: province || undefined,
      city: city || undefined,
      district: district || undefined,
      keyword: keyword || undefined,
      fuzzy: isFuzzy,
    });

    res.status(200).json({
      success: true,
      message: '搜索地理位置成功',
      data: results,
      totalCount: results.length,
    });
  } catch (error) {
    console.error('搜索地理位置失败:', error);
    res.status(500).json({
      success: false,
      message: '搜索地理位置失败',
      error: error instanceof Error ? error.message : '未知错误',
    });
  }
};

/**
 * @swagger
 * /api/location/oil-price:
 *   post:
 *     summary: 根据地理位置查询油价
 *     tags: [地理位置]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - province
 *             properties:
 *               province:
 *                 type: string
 *                 description: 省份名称
 *               city:
 *                 type: string
 *                 description: 城市名称（可选）
 *               district:
 *                 type: string
 *                 description: 区县名称（可选）
 *               fuelType:
 *                 type: string
 *                 enum: ['92', '95', '98', '0']
 *                 description: 燃油类型
 *               includeNearby:
 *                 type: boolean
 *                 description: 是否包含周边地区
 *     responses:
 *       200:
 *         description: 查询成功
 *       400:
 *         description: 请求参数错误
 *       500:
 *         description: 服务器内部错误
 */
export const getOilPriceByLocation = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const {
      province,
      city,
      district,
      fuelType,
      includeNearby = false,
    } = req.body as OilPriceByLocationRequest;

    if (!province) {
      res.status(400).json({
        success: false,
        message: '省份名称不能为空',
      });
      return;
    }

    const locationService = LocationService.getInstance();
    const oilPriceService = OilPriceService.getInstance();

    // 获取地理位置信息
    const locationData = await locationService.getOilPriceByLocation({
      province,
      city,
      district,
      fuelType,
      includeNearby,
    });

    if (!locationData.success || !locationData.data) {
      res.status(400).json({
        success: false,
        message: locationData.message || '获取地理位置油价数据失败',
      });
      return;
    }

    // 获取油价数据
    let oilPriceData;
    try {
      oilPriceData = await oilPriceService.getOilPrices(province, true);
    } catch (error) {
      console.warn('获取油价数据失败，使用模拟数据:', error);
      oilPriceData = [
        {
          province,
          price92: 7.56,
          price95: 8.05,
          price98: 9.05,
          price0: 7.23,
          updateTime: new Date(),
          source: 'eastmoney',
        },
      ];
    }

    // 过滤燃油类型
    let filteredOilPrice = oilPriceData;
    if (fuelType && oilPriceData.length > 0) {
      const price = oilPriceData[0];
      if (price) {
        switch (fuelType) {
          case '92':
            filteredOilPrice = [
              {
                province: price.province,
                price92: price.price92,
                price95: 0,
                price98: 0,
                price0: 0,
                updateTime: price.updateTime,
                source: price.source,
              },
            ];
            break;
          case '95':
            filteredOilPrice = [
              {
                province: price.province,
                price92: 0,
                price95: price.price95,
                price98: 0,
                price0: 0,
                updateTime: price.updateTime,
                source: price.source,
              },
            ];
            break;
          case '98':
            filteredOilPrice = [
              {
                province: price.province,
                price92: 0,
                price95: 0,
                price98: price.price98,
                price0: 0,
                updateTime: price.updateTime,
                source: price.source,
              },
            ];
            break;
          case '0':
            filteredOilPrice = [
              {
                province: price.province,
                price92: 0,
                price95: 0,
                price98: 0,
                price0: price.price0,
                updateTime: price.updateTime,
                source: price.source,
              },
            ];
            break;
        }
      }
    }

    // 构建响应数据
    const responseData = {
      location: locationData.data.location,
      oilPrice: filteredOilPrice[0] || {
        province,
        price92: 0,
        price95: 0,
        price98: 0,
        price0: 0,
        updateTime: new Date(),
        source: 'unknown',
      },
    };

    // 如果包含周边地区，添加周边油价信息
    if (includeNearby && oilPriceData.length > 1) {
      const nearbyPrices = oilPriceData.slice(1, 6).map((price, index) => ({
        location: price.province,
        price92: price.price92,
        price95: price.price95,
        price98: price.price98,
        price0: price.price0,
        distance: (index + 1) * 50, // 模拟距离
      }));

      (responseData as any).nearbyPrices = nearbyPrices;
    }

    res.status(200).json({
      success: true,
      message: '根据地理位置查询油价成功',
      data: responseData,
      lastUpdate: new Date(),
    });
  } catch (error) {
    console.error('根据地理位置查询油价失败:', error);
    res.status(500).json({
      success: false,
      message: '根据地理位置查询油价失败',
      error: error instanceof Error ? error.message : '未知错误',
    });
  }
};

/**
 * @swagger
 * /api/location/initialize:
 *   post:
 *     summary: 初始化地理位置数据
 *     tags: [地理位置]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 初始化成功
 *       500:
 *         description: 服务器内部错误
 */
export const initializeLocationData = async (
  _req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const locationService = LocationService.getInstance();
    await locationService.initialize();

    res.status(200).json({
      success: true,
      message: '地理位置数据初始化成功',
      data: {
        timestamp: new Date(),
        message: '地理位置数据已加载到内存和本地文件',
      },
    });
  } catch (error) {
    console.error('初始化地理位置数据失败:', error);
    res.status(500).json({
      success: false,
      message: '初始化地理位置数据失败',
      error: error instanceof Error ? error.message : '未知错误',
    });
  }
};

/**
 * @swagger
 * /api/location/cache/stats:
 *   get:
 *     summary: 获取缓存统计信息
 *     tags: [地理位置]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 获取成功
 *       500:
 *         description: 服务器内部错误
 */
export const getCacheStats = async (
  _req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const locationService = LocationService.getInstance();
    const stats = locationService.getCacheStats();

    res.status(200).json({
      success: true,
      message: '获取缓存统计信息成功',
      data: stats,
    });
  } catch (error) {
    console.error('获取缓存统计信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取缓存统计信息失败',
      error: error instanceof Error ? error.message : '未知错误',
    });
  }
};

/**
 * @swagger
 * /api/location/cache/clear:
 *   post:
 *     summary: 清除缓存
 *     tags: [地理位置]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 清除成功
 *       500:
 *         description: 服务器内部错误
 */
export const clearCache = async (
  _req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const locationService = LocationService.getInstance();
    locationService.clearCache();

    res.status(200).json({
      success: true,
      message: '缓存清除成功',
      data: {
        timestamp: new Date(),
        message: '所有缓存数据已清除',
      },
    });
  } catch (error) {
    console.error('清除缓存失败:', error);
    res.status(500).json({
      success: false,
      message: '清除缓存失败',
      error: error instanceof Error ? error.message : '未知错误',
    });
  }
};
